import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { AsyncThunk, ActionReducerMapBuilder, PayloadAction, Slice } from '@reduxjs/toolkit'
import { getList, type GetListParams } from './withdrawRecordAPI'
import { DataType } from "@/pages/WithdrawRecord/Table";
import { TZ } from "@/utils/env";
import dayjs from '@/utils/dayjs'
import { v4 } from "uuid";
import { Key } from "react";

const threeDaysAgoStart = dayjs().tz(TZ).subtract(3, 'day').unix();
const todayEnd = dayjs().tz(TZ).unix();

interface InitialState {
  params: GetListParams,
  table: {
    status: 'init' | 'loading' | 'success' | 'error',
    data: Res | undefined,
    params?: GetListParams
  },
  selectedRowKeys: Key[],
  modal: {
    open: boolean,
    wd_list_str: number[],
  }
}

const initialState: InitialState = {
  params: {
    page: 1,
    page_size: 10,
    start_time: threeDaysAgoStart,
    end_time: todayEnd,
    status: '',
    channel: '',
    method_to_addr: '',
    query_user_id: "",
    country: "",
    trade_id: ""
  },
  table: {
    status: "init",
    data: undefined,
  },
  selectedRowKeys: [],
  modal: {
    open: false,
    wd_list_str: [],
  }
};

type Res = {
  data: {
    total: number,
    page: number,
    data: DataType[]
  }
}
type AsyncRes = {
  data: Res,
  params: GetListParams
}
export const getListAsync: AsyncThunk<AsyncRes, GetListParams, {}> = createAsyncThunk<AsyncRes, GetListParams, {}>(
  "withdrawRecord/getListAsync",
  async (params) => {
    const res: Res = await getList(params);
    return {
      data: res,
      params
    };
  }
);
const tableStatus: (builder: ActionReducerMapBuilder<InitialState>) => void = (builder: ActionReducerMapBuilder<InitialState>): void => {
  builder
    .addCase(getListAsync.pending, (state: InitialState): void => {
      state.table.status = "loading";
    })
    .addCase(getListAsync.fulfilled, (state: InitialState, action: PayloadAction<AsyncRes>): void => {
      state.table.status = "success";
      if (Array.isArray(action.payload?.data?.data?.data)) {
        action.payload.data.data.data.forEach(i => i.uuid = v4())
      }
      state.table.data = action.payload.data;
      state.table.params = action.payload.params
    })
    .addCase(getListAsync.rejected, (state: InitialState): void => {
      state.table.status = "error";
    });
};

type Reducers = {
  changeParams: (state: InitialState, action: PayloadAction<Partial<GetListParams>>) => void,
  changeSelectedRowKeys: (state: InitialState, action: PayloadAction<InitialState['selectedRowKeys']>) => void,
  changeModal: (state:InitialState, action:PayloadAction<Partial<InitialState['modal']>>) => void
}
type Selectors = {}
const withdrawRecordSlice: Slice<InitialState, Reducers, 'withdrawRecord', 'withdrawRecord', Selectors> = createSlice<InitialState, Reducers, 'withdrawRecord', Selectors, 'withdrawRecord'>({
  name: "withdrawRecord",
  initialState,
  reducers: {
    changeParams(state: InitialState, action: PayloadAction<Partial<GetListParams>>): void {
      state.params = {
        ...state.params,
        ...action.payload,
      };
    },
    changeSelectedRowKeys(state, action) {
      state.selectedRowKeys = action.payload
    },
    changeModal(state, action){
      state.modal = {
        ...state.modal,
        ...action.payload
      }
    }
  },
  extraReducers(builder: ActionReducerMapBuilder<InitialState>): void {
    tableStatus(builder);
  },
});

export const { changeParams, changeSelectedRowKeys, changeModal }: typeof withdrawRecordSlice.actions = withdrawRecordSlice.actions;

export default withdrawRecordSlice.reducer;
